class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
    }
    // 得到主表数据
    GetEntityData() {
        let item = {};
        item['headerId'] = $("#HeaderId").val();
        item['billType'] = 2;                                                            // 单据类型 0：提前组料 1：定版调达 2：辅资材
        item['moHeaderId'] = $.trim($("#MoHeaderId").val());
        item['productId'] = $.trim($("#StyleNo").val());                                 // 得到产品标识
        item['styleNo'] = $.trim($("#StyleNo").find("option:selected").text());          // 得到款号（用来寻找提前组料单）
        item['bomHeaderId'] = $.trim($("#BomHeaderId").val());                           // 计算用单耗
        item['preparedBy'] = $.trim($("#PreparedBy").val());                             // 制表人
        item['preparedDate'] = $.trim($("#PreparedDate").val());                         // 制表日期
        item['isIncludeSample'] = $("#IsIncludeSample").is(":checked") ? true : false;   // 是否包含样品数
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());
        item['workFlowId'] = $.trim($("#WorkFlowId").val());
        return item;
        //return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        $("#MoHeaderId").val(item.moHeaderId);        // 生产指示书标识
        $("#BomHeaderId").val(item.bomHeaderId);      // 单耗标识
        $("#StyleNo").empty();
        let options = [];
        options.push('<option value="', item.productId, '">', item.styleNo, '</option>');
        $("#StyleNo").html(options.join(''));                           // 款号
        $("#ContractNo").val(item.contractNo);                          // 合同号
        $("#CustomerName").val(item.customerName);                      // 客户
        $("#TotalQuantity").val(item.totalQuantity);                    // 生产数
        $("#PreparedBy").val(item.preparedBy);                          // 制表人
        $("#PreparedByName").val(item.preparedByName);                  // 制表人
        $("#PreparedDate").val(item.preparedDate);                      // 制表日期
        $("#BomDescription").empty();                                   // 单耗备注（用于区分选择的单耗】
        options = [];
        options.push('<option value="', item.bomHeaderId, '">', item.bomDescription, '</option>');
        $("#BomDescription").html(options.join(''));
        $("#Notes").val(item.notes);
        $("#IcLabDipIndication").val(item.icLabDipIndication);
        $("#EmbroideryLaceAndOther").val(item.embroideryLaceAndOther);
        $("#SaledByName").val(item.saledByName);                        // 贸易担当
        $("#DesignedByName").val(item.designedByName);                  // 设计担当
        $("#GradedByName").val(item.gradedByName);                      // 单耗员
        $("#UpdatedByName").val(item.updatedByName);                    // 操作员
        $("#UpdatedDate").val(formatNullData(item.updatedDate));        // 操作日期
        $("#QuotedFlag").val(item.quotedFlag === true ? 1 : 0);         // 被采购合同引用标记

        // 是否包含样品数
        if (item.isIncludeSample === true) {
            $("#IsIncludeSample").prop("checked", true);
        } else {
            $("#IsIncludeSample").prop("checked", false);
        }
        // 最后的审核人、审核日期
        $("#CheckedBy").val(item.checkedBy);
        $("#CheckedByName").val(item.checkedByName);
        $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
        $("#CheckedStatus").val(item.checkedStatus);
        $('#FlowOrderNo').val(item.flowOrderNo);

        $("#StyleNo_02").html("【款号：" + item.styleNo + "】");
        $("#StyleNo_03").html("【款号：" + item.styleNo + "】");
        $("#StyleNo_04").html("【款号：" + item.styleNo + "】");

        if (item.poNoticeFlag === true) {
            $("#NoticedTip").removeClass().addClass("huzo_status").addClass("huzo_status__green");
            $("#NoticedTip").html("通知：已发送");
            $("#notice_user_list").empty();
            let _users_item = "";
            let _users_list = data.PurchasedByNameList;
            for (let i = 0; i < _users_list.length; i++) {
                _users_item += '<li>' + _users_list[i].purchasedbyname + '</li>';
            }
            $("#notice_user_list").html(_users_item);
            $("#area_notice").show();
        } else {
            $("#NoticedTip").removeClass().addClass("huzo_status").addClass("huzo_status__red");
            $("#NoticedTip").html("未通知采购");
            $("#notice_user_list").empty();
            $("#area_notice").hide();
        }

        if (item.poOpeningRows === true || item.poOverFlag === true) {
            $("#PoOverTip").removeClass().addClass("huzo_status").addClass("huzo_status__green");
            $("#PoOverTip").html("采购：完成");
            $("#PoOverFlag").prop("checked", true);  // 设置完成标记
        } else {
            if (item.quotedFlag === false) {
                $("#PoOverTip").removeClass().addClass("huzo_status").addClass("huzo_status__red");
                $("#PoOverTip").html("未采购");
                $("#PoOverFlag").prop("checked", false);
            } else {
                $("#PoOverTip").removeClass().addClass("huzo_status").addClass("huzo_status__yellow");
                $("#PoOverTip").html("采购：进行中");
                $("#PoOverFlag").prop("checked", false);
            }
        }

        // 设置发货目的地
        _InstancePageLinesMo.destinationNode = data.DestinationNode;
        // 设置交付日期
        _InstancePageLinesMo.scheduleNode = data.ScheduleNode;
        // 显示生产数量明细数据
        _InstancePageLinesMo.BuildDataTable(data.MoLinesList);
        // 得到相关配色方案用成品色
        _InstancePageLinesAssortment.productColourNode = data.ProductColourNode;
        // 显示搭配明细数据
        _InstancePageLinesAssortment.BuildDataTableHeader();
        _InstancePageLinesAssortment.BuildDataTable(data.AssortmentLinesList);
        // 显示物料需求明细
        _InstancePageLinesMrp.BuildDataTable(data.MrpLinesList);

        $("#menu_02").show();
        $("#menu_03").show();
        $("#menu_04").show();

        // 编辑状态时不允许更改款号
        $("#ChoiceContractNo").attr("onclick", "");
        $("#ContractNo").css({"cursor": "default"});

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;
        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            //_InstancePageLines.AutoAdjustTableHeightForLines();
        });

        if (this.pageStatus === 4) {
            $("#panelTop_02").remove();
            $("#ButNotice").remove();
            $("#ButPrint").remove();
            $("Button.act__save").remove();
            $("span.act__delete").removeClass("trash");
            $("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
        }

        $("#ContractNo").focus();
    }
    Save() {
        // 只有登录者=制表人 才可以操作，否则废除错误提示
        if ($("#UserId").val() !== $("#PreparedBy").val()) {
            if ($("#RoleName").val().indexOf("系统管理员") === -1) {
                ShowErrorMessagePanel('错误提示：您不是制表人，无法进行操作。');
                return false;
            }
        }

        if (($("#BomeHeaderId").val() === '') || (parseInt($("#BomHeaderId").val()) === 0)) {
            ShowErrorMessagePanel('错误信息：该款号没有对应单耗或者单耗没有通过审核。');
            return false;
        }

        if (parseInt(this.pageStatus) === 1) {
            super.DoAjax(this.GetEntityData(), "/tech/mrp/header/insert.html", function (data, _this) {
                _this.FillData(data);
                _this.dataId = data.HeaderEntity;
                $("#Action").val(2);
                $("#ButPrint").show();
                $("#CheckedTip").removeClass().addClass("huzo_status").addClass("huzo_status__red");
                $("#CheckedTip").html("状态：未审核");
                $("#CheckedTip").show();
                _this.pageStatus = 2;
                ShowSuccessMessagePanel('增加成功。');
            });
        } else {
            super.DoAjax(this.GetEntityData(), "/tech/mrp/header/update.html", function (data, _this) {
                if (data > 0)
                    ShowSuccessMessagePanel('更新成功。');
            });
        }
    }
    New() {
        super.New();
        $("#HeaderId").val(0);
        $("#panelSlave").hide();
        // 新增状态时允许更改款号
        let _event_onclick = '_InstancePageHeader.DoChoiceContractNo()';
        $("#ChoiceContractNo").attr("onclick", _event_onclick);
        $("#ContractNo").css({"cursor": "pointer"});

        // 默认设置一些值
        $("#IsIncludeSample").prop("checked", false);
        $("#StyleNo").attr("disabled", false);
        $("#StyleNo").empty();
        $("#BomDescription").attr("disabled", false);
        $("#BomDescription").empty();
        $("#UpdatedBy").val($("#UserId").val());
        $("#UpdatedByName").val($("#UserName").val());
        $("#UpdatedDate").val(getCurrentDate());
        $("#PreparedBy").val($("#UserId").val());
        $("#PreparedByName").val($("#UserName").val());
        $("#PreparedDate").val(getCurrentDate());        // 制表日期

        $("#ButExportToExcel1").hide();   // 隐藏导出按钮
        $("#ButExportToExcel2").hide();   // 隐藏导出按钮

        $("#menu_02").hide();
        $("#menu_03").hide();
        $("#menu_04").hide();
        $("#ButSaveLinesResult").show();
        $("#ButUndo").show();
        $("#ButReCalculate").show();
        $("#ButNotice").hide();               // 发送通知按钮
        $("#area_notice").hide();             // 隐藏采购通知区域
        $("#ButOverSwitcher").hide();         // 隐藏采购完成开关

        $(".huzo_notice_container").hide();   // 清空发送给的通知者
        $("#notice_user_list").empty();
        $("#NoticedTip").hide();
        $("#PoOverTip").hide();

        $('#tabData11 tbody').empty();
        $('#tabData12 tbody').empty();
        $("#panelSlave").hide();

        $("#ContractNo").focus();
    }
    // 以下为选择框
    DoChoicePreparedBy() {
        let _choice = new CommonChoice();
        _choice.DoChoiceUser(0, '选择制表人', '设计', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#PreparedByName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#PreparedBy").val(data[0]);
                $("#PreparedByName").val(data[1]);
                $("#PreparedByName").focus();
            }
        });
        $("#PreparedByName").focus();
    }
    // 选择合同号（生产指示书)
    DoChoiceContractNo() {
        let _choice = new CommonChoice();
        _choice.DoChoiceMo(0, '选择合同号', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#ContractNo").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#MoHeaderId").val(data[0]);   // MoId
                $("#ContractNo").val(data[1]);   // 合同号
                $("#CustomerName").val(data[2]);
                $("#TotalQuantity").val(data[3]);
                $("#SaledByName").val(data[4]);

                // 根据生产指示书得到款号
                super.DoAjax(data[0], "/trade/production_instruction/header/fetchStyleNoByHeaderKey.html", function (data, _this) {
                    if (data !== null) {
                        $("#StyleNo").empty();
                        let options = [];
                        options.push('<option value="-1">-- 请选择 --</option>');
                        for (let i = 0; i < data.length; i++) {
                            options.push('<option value="', data[i].productId, '">', data[i].styleNo, '</option>');
                        }
                        $("#StyleNo").html(options.join(''));
                    } else {
                        ShowErrorMessagePanel('错误信息：该合同没有款号信息。');
                    }
                });
            }
        });
        $("#ContractNo").focus();
    }
    // 根据款号、单耗类型，取得单耗信息供选择
    FetchBomInfo(bomType) {
        let criterion = {};
        criterion['StyleNo'] = $.trim($("#StyleNo").find("option:selected").text());
        criterion['TypeFlag'] = bomType;  // 单耗类型 0：正常 1：副资材

        super.DoAjax(criterion, "/tech/piece_yardage_onesize/fetchByStyleNo.html", function (data, _this) {
            $("#BomDescription").empty();
            if (data !== null && data.length > 0) {
                let options = [];
                options.push('<option value="-1">-- 请选择 --</option>');
                for (let i = 0; i < data.length; i++) {
                    let _item = '<option value="' + data[i].headerId + '" ';
                    _item += '_mash_ic_labdip_indication="' + formatNullData(data[i].icLabDipIndication) + '" ';
                    _item += '_mash_embroiderylace_and_other="' + formatNullData(data[i].embroideryLaceAndOther) + '" ';
                    _item += '_mash_notes="' + formatNullData(data[i].notes) + '" ';
                    _item += '_mash_designed="' + formatNullData(data[i].designedByName) + '" ';
                    _item += '_mash_graded="' + formatNullData(data[i].gradedByName) + '">';
                    _item += formatNullData(data[i].description) + '</option>';

                    options.push(_item);
                }
                $("#BomDescription").html(options.join(''));
            } else {
                ShowErrorMessagePanel('错误信息：该款号没有对应单耗表。');
            }
        });
    }
    // 根据选择的单耗，设置单耗其他信息
    SetBomInfo() {
        let $option = $("#BomDescription").find("option:selected");
        if ($("#BomDescription").val() === "-1") {
            $("#BomHeaderId").val();
            $("#IcLabDipIndication").val("");
            $("#EmbroideryLaceAndOther").val("");
            $("#DesignedByName").val("");
            $("#GradedByName").val("");
        } else {
            $("#BomHeaderId").val($("#BomDescription").val());
            $("#IcLabDipIndication").val($option.attr("_mash_ic_labdip_indication"));
            $("#EmbroideryLaceAndOther").val($option.attr("_mash_embroiderylace_and_other"));
            $("#DesignedByName").val($option.attr("_mash_designed"));
            $("#GradedByName").val($option.attr("_mash_graded"));
        }
        $("#Notes").val($option.attr("_mash_notes"));
    }
    // 发送采购下单通知
    SendNotice() {
        let _choice = new CommonChoice();
        _choice.DoChoiceUserGroupMember(1, '选择要通知的采购担当', (data) => {
            if (data) {
                let _result = [];
                for (let i = 0; i < data.length; i++) {
                    let item = {};
                    item['mrpId'] = parseInt($("#HeaderId").val());
                    //item['styleNo'] = $.trim($("#StyleNo").text());
                    item['purchasedBy'] = data[i]['UserId'];
                    item['updatedBy'] = parseInt($("#UserId").val());
                    item['createdBy'] = parseInt($("#UserId").val());
                    item['billType'] = "0";   // 表示副资材
                    _result.push(item);
                }

                // 发送通知
                super.DoAjax(_result, "/purchase/po_notice/sendPoNotice.html", function (data, _this) {
                    if (data.Result.length > 0) {
                        $("#NoticedTip").removeClass().addClass("huzo_status").addClass("huzo_status__green");
                        $("#NoticedTip").html("通知：已发送");
                        $("#notice_user_list").empty();
                        let _users_item = "";
                        for (let i = 0; i < data.Result.length; i++) {
                            _users_item += '<li>' + (data.Result)[i].purchasedbyname + '</li>';
                        }
                        $("#notice_user_list").html(_users_item);
                        $("#area_notice").show();
                        ShowSuccessMessagePanel("采购下单通知发送成功。");
                    } else {
                        ShowErrorMessagePanel("采购下单通知发送失败。");
                    }
                });
            }
        });
    }
    DoPrintPreview() {
        window.open(parent.basePath + this.printUrl + "?id=" + $("#HeaderId").val() + "&moId=" + $("#MoHeaderId").val() + "&productId=" + $("#StyleNo").val());
    }
    // 导出到Excel
    ExportDataWithMoFormat() {
        $("#export_form").attr("action", parent.basePath + "/tech/mrp/export_to_excel.html");
        $("#ExportHeaderId").val($("#HeaderId").val());
        $("#ExportMoHeaderId").val($("#MoHeaderId").val());
        $("#ExportBomHeaderId").val($("#BomHeaderId").val());
        $("#ExportProductId").val($('#StyleNo').val());
        $("#ExportStyleNo").val($('#StyleNo option:selected').text());
        $("#export_form").submit();
    }
    ShowPageElement() {
        $("Button.act__save").show();
        if (!$("span.act__delete").hasClass("act__delete")) {
            $("span.act__delete").addClass("trash");
            $("span.act__delete i").addClass("fa-all fa-trash-o fa-1");
        }
    }
    HidePageElement() {
        //$("Button.act__save").hide();
        //$("span.act__delete").removeClass("trash");
        //$("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
    }
    // 设置完成状态
    SetPoOverFlag() {
        let _params = {};
        _params['HeaderId'] = parseInt($("#HeaderId").val());
        _params['CurrentUserId'] = parseInt($("#UserId").val());
        _params['WorkFlowId'] = $("#WorkFlowId").val() === '' ? 0 : parseInt($("#WorkFlowId").val());
        _params['PoOverFlag'] = $("#PoOverFlag").is(":checked") ? true : false;  // 完成标记

        this.DoAjax(_params, "/tech/mrp/setPoOverFlag.html", (data) => {
            if ($("#PoOverFlag").is(":checked")) {
                $("#PoOverTip").removeClass().addClass("huzo_status").addClass("huzo_status__green");
                $("#PoOverTip").html("采购：完成");
                // 采购完成后不再允许变更该调达表
                $("button.act__save").hide();
                $("button.act__notice").hide();
                $("button.act__check").hide();
            } else {
                if (data.HeaderEntity !== null) {
                    let item = data.HeaderEntity;
                    if (item.quotedFlag === false) {
                        $("#PoOverTip").removeClass().addClass("huzo_status").addClass("huzo_status__red");
                        $("#PoOverTip").html("未采购");
                    } else {
                        if (item.poOpeningRows === true) {
                            $("#PoOverTip").removeClass().addClass("huzo_status").addClass("huzo_status__green");
                            $("#PoOverTip").html("采购：完成");
                        } else {
                            $("#PoOverTip").removeClass().addClass("huzo_status").addClass("huzo_status__yellow");
                            $("#PoOverTip").html("采购：进行中");
                        }
                    }
                }
            }
            ShowSuccessMessagePanel("完成状态设置成功。");
        });
    }
}

class MyPageLinesMo extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.scheduleNode = null;
        this.destinationNode = null;
    }
    BuildDataTable(result) {
        $('#tabData11 tbody').empty();
        $('#tabData12 tbody').empty();

        // 得到数据列表
        if (result === null) {
            this.rows = 0;
            // 自适应高度
            this.AutoAdjustTableHeightForLines();
            return false;
        }
        let content_01 = '';
        let content_02 = '';

        // 设置左侧表头高度
        if (_InstancePageLinesMo.destinationNode.length > 0) {
            $("#tabHeader11 thead tr th").addClass("report");
            $("#tabHeader11 thead tr").css("height", "54px");
        } else {
            $("#tabHeader11 thead tr th").removeClass("report");
            $("#tabHeader11 thead tr").css("height", "");
        }
        // 第一步：设置列宽度
        $("#tabHeader12 colgroup").empty();
        $("#tabData12 colgroup").empty();
        content_02 += '<col style="width:120px;" />';
        content_02 += '<col style="width:80px;" />';
        let _tw = 120 + 80;
        if (_InstancePageLinesMo.destinationNode.length > 0) {
            for (let i = 0; i < _InstancePageLinesMo.destinationNode.length; i++) {
                for (let j = 0; j < _InstancePageLinesMo.scheduleNode.length; j++) {
                    content_02 += '<col style="width:100px;" />';
                    _tw = _tw + 100;
                }
            }
        } else {
            // 增加交货期        
            for (let i = 0; i < _InstancePageLinesMo.scheduleNode.length; i++) {
                content_02 += '<col style="width:100px;" />';
                _tw = _tw + 100;
            }
        }
        let w = $(window).width() - 530 - 200 - 16 - 17;
        let _w_desc = (w - _tw) < 400 ? 400 : (w - _tw);
        content_02 += '<col style="width:' + _w_desc + 'px;" />';
        _tw += _w_desc;
        $("#tabHeader12 colgroup").append(content_02);
        $("#tabData12 colgroup").append(content_02);

        // 第二步：设置表头
        content_02 = '';
        $("#tabHeader12 thead").empty();
        if (_InstancePageLinesMo.destinationNode.length > 0) {
            content_02 += '<tr>';
            content_02 += '<th rowspan="2" class="report">唛头号</th>';
            content_02 += '<th rowspan="2" class="report">样品数</th>';
            for (let i = 0; i < _InstancePageLinesMo.destinationNode.length; i++) {
                content_02 += '<th class="cell_01" style="text-align:center;" colspan="' + _InstancePageLinesMo.scheduleNode.length + '">' + _InstancePageLinesMo.destinationNode[i].destination + '</th>';
            }
            content_02 += '<th rowspan="2" class="report" style="border-right:none;">备注</th>';
            content_02 += '</tr>';
            content_02 += '<tr>';
            for (let i = 0; i < _InstancePageLinesMo.destinationNode.length; i++) {
                if (_InstancePageLinesMo.scheduleNode.length > 0) {
                    for (let i = 0; i < _InstancePageLinesMo.scheduleNode.length; i++) {
                        content_02 += '<th class="cell_02" style="text-align:center;">' + _InstancePageLinesMo.scheduleNode[i] + '</th>';
                    }
                }
            }
            content_02 += '</tr>';
        } else {
            content_02 += '<tr>';
            content_02 += '<th>唛头号</th>';
            content_02 += '<th>样品数</th>';
            if (_InstancePageLinesMo.scheduleNode.length > 0) {
                for (let i = 0; i < _InstancePageLinesMo.scheduleNode.length; i++) {
                    content_02 += '<th>' + _InstancePageLinesMo.scheduleNode[i] + '</th>';
                }
            }
            content_02 += '<th style="border-right:none;">备注</th>';
            content_02 += '</tr>';
        }
        $("#tabHeader12 thead").append(content_02);

        // 第三步：设置表体
        content_01 = '';
        content_02 = '';
        this.rows = result.length;  // 设置表格记录数
        this.numCheckbox = result.length;
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            if (parseInt(result[i].rowFlag) === 0) {
                content_01 += '<tr _mash_id="' + id + '" _mash_colourId="' + result[i].colourId + '">';
                if (i > 0) {
                    if (result[i].colourId === result[i - 1].colourId) {
                        content_01 += '<td style="border-bottom:none;"></td>';
                        content_01 += '<td style="border-bottom:none;"></td>';
                    } else {
                        content_01 += '<td style="border-top:1px solid #c6c3bd; border-bottom:none;">' + formatNullData(result[i].colourNumber) + '</td>';
                        content_01 += '<td style="border-top:1px solid #c6c3bd; border-bottom:none;">' + formatNullData(result[i].colourName) + '</td>';
                    }
                } else {
                    content_01 += '<td style="border-bottom:none;">' + formatNullData(result[i].colourNumber) + '</td>';
                    content_01 += '<td style="border-bottom:none;">' + formatNullData(result[i].colourName) + '</td>';
                }
                content_01 += '<td>' + formatNullData(result[i].suitSizeName) + '&nbsp;</td>';
            } else {
                if (parseInt(result[i].rowFlag) === 1) {
                    content_01 += '<tr style="background-color:#ffe4b5; color:#000">';
                    content_01 += '<td colspan="3" style="border-top:1px solid #c6c3bd; text-align:center;">小计</td>';
                } else {
                    content_01 += '<tr style="background-color:#00f9fc; color:#000;">';
                    content_01 += '<td colspan="3" style="border-top:1px solid #c6c3bd; text-align:center; font-weight:bold;">总计</td>';
                }
            }
            content_01 += '<td>' + (parseInt(result[i].rowSubTotal) === 0 ? '' : formatNullData(result[i].rowSubTotal)) + '</td>';
            content_01 += '</tr>';

            if (parseInt(result[i].rowFlag) === 0) {
                content_02 += '<tr>';
                content_02 += '<td>' + formatNullData(result[i].shippingMarkNo) + '</td>';
                content_02 += '<td>' + formatNullData(result[i].sampleQuantity === 0 ? '' : result[i].sampleQuantity) + '</td>';
                // 显示目的地分配数量情况
                if (_InstancePageLinesMo.destinationNode.length > 0) {
                    for (let j = 0; j < _InstancePageLinesMo.destinationNode.length; j++) {
                        let _destination = _InstancePageLinesMo.destinationNode[j].destination;
                        for (let k = 0; k < _InstancePageLinesMo.scheduleNode.length; k++) {
                            let _deliveryDate = _InstancePageLinesMo.scheduleNode[k];
                            let _t = false;
                            $.each(result[i].schemaMemoJson, function (index, data) {
                                if (data.Destination === _destination && data.DeliveryDate === _deliveryDate) {
                                    content_02 += '<td>' + formatNullData(data.Quantity) + '</td>';
                                    _t = true;
                                    return false;
                                }
                            });
                            if (_t === false)
                                content_02 += '<td class="edited-cell"></td>';
                        }
                    }
                } else {
                    for (let j = 0; j < _InstancePageLinesMo.scheduleNode.length; j++) {
                        let _deliveryDate = _InstancePageLinesMo.scheduleNode[j];
                        let _t = false;
                        $.each(result[i].schemaMemoJson, function (index, data) {
                            if (data.DeliveryDate === _deliveryDate) {
                                content_02 += '<td>' + formatNullData(data.Quantity) + '</td>';
                                _t = true;
                                return false;
                            }
                        });
                        if (_t === false)
                            content_02 += '<td></td>';
                    }
                }
                content_02 += '<td style="border-right:none;">' + formatNullData(result[i].descripton) + '</td>';
            } else {
                if (parseInt(result[i].rowFlag) === 1) {
                    content_02 += '<tr style="background-color:#ffe4b5; color:#000;">';
                } else {
                    content_02 += '<tr style="background-color:#00f9fc; color:#000;">';
                }
                content_02 += '<td>' + formatNullData(result[i].shippingMarkNo) + '</td>';
                content_02 += '<td>' + formatNullData(result[i].sampleQuantity === 0 ? '' : result[i].sampleQuantity) + '</td>';
                // 显示目的地分配数量情况
                if (_InstancePageLinesMo.destinationNode.length > 0) {
                    for (let j = 0; j < _InstancePageLinesMo.destinationNode.length; j++) {
                        let _destination = _InstancePageLinesMo.destinationNode[j].destination;
                        for (let k = 0; k < _InstancePageLinesMo.scheduleNode.length; k++) {
                            let _deliveryDate = _InstancePageLinesMo.scheduleNode[k];
                            let _t = false;
                            $.each(result[i].schemaMemoJson, function (index, data) {
                                if (data.Destination === _destination && data.DeliveryDate === _deliveryDate) {
                                    content_02 += '<td>' + formatNullData(data.Quantity) + '</td>';
                                    _t = true;
                                    return false;
                                }
                            });
                            if (_t === false)
                                content_02 += '<td"></td>';
                        }
                    }
                } else {
                    for (let j = 0; j < _InstancePageLinesMo.scheduleNode.length; j++) {
                        let _deliveryDate = _InstancePageLinesMo.scheduleNode[j];
                        let _t = false;
                        $.each(result[i].schemaMemoJson, function (index, data) {
                            if (data.DeliveryDate === _deliveryDate) {
                                content_02 += '<td>' + formatNullData(data.Quantity) + '</td>';
                                _t = true;
                                return false;
                            }
                        });
                        if (_t === false)
                            content_02 += '<td></td>';
                    }
                }
                content_02 += '<td style="border-right:none;">' + formatNullData(result[i].descripton) + '</td>';
            }
            content_02 += '</tr>';
            $('#tabData11 tbody').append(content_01);
            $('#tabData12 tbody').append(content_02);
            content_01 = '';
            content_02 = '';
        }
        setTwoTableRowColor("tabData11", "tabData12");
        this.AutoAdjustTableHeightForLines();
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = 219; //$("#panelSlaveData_02").offset().top + 26;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
        let _rc = 0;
        if (_InstancePageLinesMo.destinationNode !== null) {
            _rc = Math.floor((h - _tabTop - 52) / 25);
        } else {
            _rc = Math.floor((h - _tabTop - 25) / 25);
        }
        let _dh = _rc * 25 + 17;
        let _rowH = this.rows * 25 + 17; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD11").css({"max-height": _dh - 18, height: _dh - 18});
        $("#divD12").css({"max-height": _dh, height: _dh});
    }
    ScrollTo() {
        $('#divH12').scrollLeft($('#divD12').scrollLeft());
        $('#divD11').scrollTop($('#divD12').scrollTop());
    }
}

class MyPageLinesAssortment extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.productColourNode = null;
    }
    // 显示搭配类型
    ShowAssortmentType(assortmentType) {
        let _result = "";
        if (assortmentType !== null) {
            switch (parseInt(assortmentType)) {
                case 0:
                    _result = '<span class="m0">无搭配</span>';
                    break;
                case 1:
                    _result = '<span class="m1">颜色搭配</span>';
                    break;
                case 2:
                    _result = '<span class="m2">尺码搭配</span>';
                    break;
                case 3:
                    _result = '<span class="m3">色码搭配</span>';
                    break;
                case 9:
                    _result = '<span class="m0">无搭配</span>';
                    break;
            }
        }
        return _result;
    }
    BuildDataTableHeader() {
        // 形成颜色表头 
        let _th = '<th>客户用量</th>';
        _th += '<th>工厂用量</th>';
        _th += '<th>套裁用量</th>';
        _th += '<th style="text-align:center;">单位</th>';
        let _colWidth = 60 * 3 + 50;
        let _col = '<col style="width:60px;" />';
        _col += '<col style="width:60px;" />';
        _col += '<col style="width:60px;" />';
        _col += '<col style="width:40px;" />';
        if ((this.productColourNode !== null) && (this.productColourNode.length > 0)) {
            for (let i = 0; i < this.productColourNode.length; i++) {
                _col += '<col style="width:130px;" />';
                _colWidth += 130;
                _th += '<th>' + this.productColourNode[i].productColourName + '</th>';
            }
        }
        _col += '<col style="width:75px;" />';
        _th += '<th style="text-align:center;">备料来源</th>';
        _colWidth += 75;
        let w = $(window).width() - 767 - 16 - 17;
        let _w_desc = (w - _colWidth) < 400 ? 400 : (w - _colWidth);
        _col += '<col style="' + _w_desc + 'px;" />';
        _th += '<th>备注</th>';
        _colWidth += _w_desc;
        $("#tabHeader22").css({width: _colWidth});
        $("#tabData22").css({width: _colWidth});
        $("#tabHeader22 thead tr").empty();
        $("#tabHeader22 colgroup").empty();
        $("#tabData22 colgroup").empty();
        $("#tabHeader22 colgroup").html(_col);
        $("#tabData22 colgroup").html(_col);
        $("#tabHeader22 thead tr").html(_th);
    }
    BuildDataTable(result) {
        $('#tabData21 tbody').empty();
        $('#tabData22 tbody').empty();

        // 得到数据列表
        if (result === null) {
            this.rows = 0;
            return false;
        }
        let content01 = '';
        let content02 = '';
        this.rows = result.length;
        this.numCheckbox = result.length;
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            if (result[i].isCalculatedRow === true) {
                content01 += '<tr _mash_id="' + id + '">';
            } else {
                content01 += '<tr _mash_id="' + id + '" class="row__error">';
            }
            if (result[i].quotedFlag === false) {
                content01 += '<td bom_lineskey="' + result[i].bomLinesId + '"><label style="margin-left:3px;" class="btn" for="R-' + id + '"><input id="R-' + id + '" name="_check_row" type="checkbox" onclick="_InstancePageLinesAssortment.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll\'));" value="' + id + '"/><i></i><span></span></label></td>';
                content01 += '<td style="text-align:center;">' + formatNullData(result[i].orderNo) + '</td>';
                content01 += '<td class="column__action"><span title="删除" class="trash act_delete" onclick="_InstancePageLinesAssortment.DoDeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            } else {
                content01 += '<td></td>';
                content01 += '<td style="text-align:center;">' + formatNullData(result[i].orderNo) + '</td>';
                content01 += '<td></td>';
            }
            let _isCalculated = result[i].isCalculatedRow === false ? "<span class='n2'>否" : "<span class='n1'>是";
            content01 += '<td style="text-align:center;">' + _isCalculated + '</span></td>';
            content01 += '<td style="text-align:center;">' + this.ShowAssortmentType(result[i].assortmentType) + '</td>';
            content01 += '<td>' + formatNullData(result[i].materialName) + '</td>';
            content01 += '<td>' + formatNullData(result[i].supplierName) + '</td>';
            content01 += '<td style="text-overflow:ellipsis;" title="' + formatNullData(result[i].partOfNeed) + '">' + formatNullData(result[i].partOfNeed) + '</td>';
            content01 += '<td>' + formatNullData(result[i].materialCode) + '</td>';
            content01 += '<td>' + formatNullData(result[i].specification) + '</td>';
            content01 += '</tr>';

            if (result[i].isCalculatedRow === true) {
                content02 += '<tr>';
            } else {
                content02 += '<tr class="row__error">';
            }
            content02 += '<td>' + formatNullData(result[i].customerPieceYardage === 0 ? null : result[i].customerPieceYardage) + '</td>';
            content02 += '<td>' + formatNullData(result[i].factoryPieceYardage === 0 ? null : result[i].factoryPieceYardage) + '</td>';
            content02 += '<td>' + formatNullData(result[i].suitCutPieceYardage === 0 ? null : result[i].suitCutPieceYardage) + '</td>';
            content02 += '<td style="text-align:center;" _msh_uomid="' + result[i].uomId + '">' + formatNullData(result[i].uomName) + '</td>';
            // 显示颜色搭配情况
            if (this.productColourNode !== null) {
                for (let j = 0; j < this.productColourNode.length; j++) {
                    let _productColourId = this.productColourNode[j].productColourId.toString();
                    let _t = false;
                    $.each(result[i].colourSchema, function (index, data) {
                        if (data.ProductColourId === _productColourId) {
                            content02 += '<td>' + formatNullData(data.MaterialColour) + '</td>'; // 搭配的材料色
                            _t = true;
                            return false;
                        }
                    });
                    if (_t === false)
                        content02 += '<td></td>'; // 搭配的材料色
                }
            }
            content02 += '<td style="text-align:center;">' + formatNullData(result[i].materialPreparedTypeName) + '</td>';    // 物料来源
            content02 += '<td>' + formatNullData(result[i].description) + '</td>';    //
            content02 += '</tr>';
            $('#tabData21 tbody').append(content01);
            $('#tabData22 tbody').append(content02);
            content01 = '';
            content02 = '';
        }
        setTwoTableRowColor("tabData21", "tabData22");
        //自适应高度
        this.AutoAdjustTableHeightForLines();
    }
    // 删除单行
    DoDeleteLines($self) {
        // 只有登录者=制表人 才可以操作，否则废除错误提示
        if ($("#UserId").val() !== $("#PreparedBy").val()) {
            if ($("#RoleName").val().indexOf("系统管理员") === -1) {
                ShowErrorMessagePanel('错误提示：您不是制表人，无法进行操作。');
                return false;
            }
        }
        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['LinesId'] = $self.parent().parent().attr("_mash_id");
        params['DeletedBy'] = $.trim($("#UserId").val());
        params['LinesData'] = "款号：" + $.trim($("#StyleNo").find("option:selected").text()) +
                "　料号：" + $self.parent().parent().find("td").eq(8).text() +
                "　使用部位：" + $self.parent().parent().find("td").eq(7).text();
        super.DeleteLines(params, "/tech/mrp/lines/assortment/delete.html", function (data, _this) {
            // 刷新搭配明细
            _this.BuildDataTable(data.AssortmentLinesList);
            // 刷新物料需求明细
            _InstancePageLinesMrp.BuildDataTable(data.MrpLinesList);
            ShowSuccessMessagePanel("删除成功。");
        });
    }
    // 批量选择的数据
    GetCheckedLinesData() {
        let choiced_data = [];
        if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
            $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                let $tr = $(this).parent().parent().parent();
                let item = {};
                item['headerId'] = parseInt($("#HeaderId").val());
                item['linesId'] = $(this).val();
                item['materialCode'] = $.trim($tr.find("td").eq(8).text());
                item['partOfNeed'] = $.trim($tr.find("td").eq(7).text());
                item['deletedBy'] = $("#UserId").val();
                choiced_data.push(item);
            });
        }
        return JSON.stringify(choiced_data);
    }
    // 批量删除
    BatchDeleteLines() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请选择要删除的数据。");
            return false;
        }
        super.BatchDeleteLines('/tech/mrp/lines/assortment/batch_delete.html', function (data, _this) {
            // 刷新搭配明细
            _this.BuildDataTable(data.AssortmentLinesList);
            // 刷新物料需求明细
            _InstancePageLinesMrp.BuildDataTable(data.MrpLinesList);
            $("#CheckAll").prop("checked", false);
            ShowSuccessMessagePanel("批量删除完成。");
        });
    }
    SetRowStatus($self) {
        let $row = $self.parent().parent().parent();
        let rowIndex = $row.index();
        if ($self.is(":checked") === true) {
            $row.addClass("row__selected");
            $('#tabData22 tbody tr:eq(' + rowIndex + ')').addClass("row__selected");
            // 设置 编辑、删除按钮失效
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", "");
        } else {
            $row.removeClass("row__selected");
            $('#tabData22 tbody tr:eq(' + rowIndex + ')').removeClass("row__selected");
            // 设置删除按钮有效
            let _event_delete_onclick = "_InstancePageLinesAssortment.DoDeleteLines($(this))";
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", _event_delete_onclick);
        }
    }
    // 进行搭配计算
    DoAssortmentCal() {
        // 只有登录者=制表人 才可以操作，否则废除错误提示
        if ($("#UserId").val() !== $("#PreparedBy").val()) {
            if ($("#RoleName").val().indexOf("系统管理员") === -1) {
                ShowErrorMessagePanel('错误提示：您不是制表人，无法进行操作。');
                return false;
            }
        }
        if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
            showModal(330, 360, '选择计算方法', parent.basePath + '/tech/mrp/assortment_type/choice.html', null, ($dialog) => {
                let _exist = $.inArray($dialog, parent.arrDialog);
                if (_exist >= 0) {
                    parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                }
                // 做选择设置
                if (parent.choice_success) {
                    let _type = parent.arrChoice[0];                   // 搭配类型
                    let _calByDestinationFlag = parent.arrChoice[1];   // 是否使用按照发货目的地分配的数量
                    let arrDestination = [];                           // 得到选择的发货目的地
                    // 如果选择了按发货地来进行区分
                    if (_calByDestinationFlag) {
                        showModal(300, 538, '选择发货地', parent.basePath + '/tech/mrp/assortment_destination/choice.html', null, ($dialog) => {
                            let _exist = $.inArray($dialog, parent.arrDialog);
                            if (_exist >= 0) {
                                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                            }
                            // 做选择设置
                            if (parent.choice_success) {
                                arrDestination = parent.arrChoice[0];
                                // 只要不是无搭配就有可能需要选择尺码（因为有些色没有对应的码）
                                if (parseInt(_type) !== 0) {
                                    showModal(300, 538, '选择成品尺码', parent.basePath + '/tech/mrp/assortment_size/choice.html', null, ($dialog) => {
                                        let _exist = $.inArray($dialog, parent.arrDialog);
                                        if (_exist >= 0) {
                                            parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                                        }
                                        // 做选择设置
                                        if (parent.choice_success) {
                                            let itemList = [];
                                            $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                                                let item = {};
                                                item['headerId'] = parseInt($("#HeaderId").val());
                                                item['moHeaderId'] = parseInt($.trim($("#MoHeaderId").val()));
                                                item['styleNo'] = $.trim($("#StyleNo").find("option:selected").text());  // 取得款号
                                                item['bomHeaderId'] = parseInt($.trim($("#BomHeaderId").val()));
                                                item['linesId'] = $(this).val();
                                                item['assortmentType'] = _type;
                                                item['calByDestinationFlag'] = _calByDestinationFlag;
                                                item['assortmentDestination'] = arrDestination;
                                                item['assortmentSize'] = parent.arrChoice[0];
                                                item['billType'] = 0;
                                                item['updatedBy'] = $("#UserId").val();
                                                itemList.push(item);
                                            });
                                            super.DoAjax(itemList, "/tech/mrp/lines/assortment/calculate.html", function (data, _this) {
                                                _this.OnCalculated(data, _this, _type);
                                            });
                                        }
                                        // 清空数组
                                        parent.arrChoice.splice(0, parent.arrChoice.length);
                                        parent.choice_success = false;

                                    });
                                } else {
                                    // 其他类型则进行搭配计算
                                    let itemList = [];
                                    $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                                        let item = {};
                                        item['headerId'] = parseInt($("#HeaderId").val());
                                        item['moHeaderId'] = parseInt($.trim($("#MoHeaderId").val()));
                                        item['styleNo'] = $.trim($("#StyleNo").find("option:selected").text());  // 取得款号
                                        item['bomHeaderId'] = parseInt($.trim($("#BomHeaderId").val()));
                                        item['linesId'] = $(this).val();
                                        item['assortmentType'] = _type;
                                        item['calByDestinationFlag'] = _calByDestinationFlag;
                                        item['assortmentDestination'] = arrDestination;
                                        item['billType'] = 0;
                                        item['updatedBy'] = $("#UserId").val();
                                        itemList.push(item);
                                    });

                                    super.DoAjax(itemList, "/tech/mrp/lines/assortment/calculate.html", function (data, _this) {
                                        _this.OnCalculated(data, _this, _type);
                                    });
                                }
                            }
                            // 清空数组
                            parent.arrChoice.splice(0, parent.arrChoice.length);
                            parent.choice_success = false;
                        });
                    } else {
                        // 只要不是无搭配就有可能需要选择尺码（因为有些色没有对应的码）
                        if (parseInt(_type) !== 0) {
                            showModal(300, 538, '选择成品尺码', parent.basePath + '/tech/mrp/assortment_size/choice.html', null, ($dialog) => {
                                let _exist = $.inArray($dialog, parent.arrDialog);
                                if (_exist >= 0) {
                                    parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                                }
                                // 做选择设置
                                if (parent.choice_success) {
                                    let itemList = [];
                                    $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                                        let item = {};
                                        item['headerId'] = parseInt($("#HeaderId").val());
                                        item['moHeaderId'] = parseInt($.trim($("#MoHeaderId").val()));
                                        item['styleNo'] = $.trim($("#StyleNo").find("option:selected").text());  // 取得款号
                                        item['bomHeaderId'] = parseInt($.trim($("#BomHeaderId").val()));
                                        item['linesId'] = $(this).val();
                                        item['assortmentType'] = _type;
                                        item['calByDestinationFlag'] = _calByDestinationFlag;
                                        item['assortmentDestination'] = arrDestination;
                                        item['assortmentSize'] = parent.arrChoice[0];
                                        item['billType'] = 0;
                                        item['updatedBy'] = $("#UserId").val();
                                        itemList.push(item);
                                    });
                                    super.DoAjax(itemList, "/tech/mrp/lines/assortment/calculate.html", function (data, _this) {
                                        _this.OnCalculated(data, _this, _type);
                                    });
                                }
                                // 清空数组
                                parent.arrChoice.splice(0, parent.arrChoice.length);
                                parent.choice_success = false;

                            });
                        } else {
                            // 其他类型则进行搭配计算
                            let itemList = [];
                            $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                                let item = {};
                                item['headerId'] = parseInt($("#HeaderId").val());
                                item['moHeaderId'] = parseInt($.trim($("#MoHeaderId").val()));
                                item['styleNo'] = $.trim($("#StyleNo").find("option:selected").text());  // 取得款号
                                item['bomHeaderId'] = parseInt($.trim($("#BomHeaderId").val()));
                                item['linesId'] = $(this).val();
                                item['assortmentType'] = _type;
                                item['calByDestinationFlag'] = _calByDestinationFlag;
                                item['assortmentDestination'] = arrDestination;
                                item['billType'] = 0;
                                item['updatedBy'] = $("#UserId").val();
                                itemList.push(item);
                            });

                            super.DoAjax(itemList, "/tech/mrp/lines/assortment/calculate.html", function (data, _this) {
                                _this.OnCalculated(data, _this, _type);
                            });
                        }
                    }
                }
                // 清空数组
                parent.arrChoice.splice(0, parent.arrChoice.length);
                parent.choice_success = false;
            });
        } else {
            ShowErrorMessagePanel("请选择要进行搭配计算的材料。");
        }
    }
    // 计算完成后的操作
    OnCalculated(data, _this, type) {
        if (data.Success === true) {
            _this.BuildDataTable(data.AssortmentLinesList);
            // 刷新调达表
            _InstancePageLinesMrp.BuildDataTable(data.MrpLinesList);
            /*
             $("input[type='checkbox'][name='_check_row']:checked").each(function () {
             let $row = $(this).parent().parent().parent();
             $row.children('td').eq(4).html(_this.ShowAssortmentType(type));
             let _rowIndex = $(this).parent().parent().parent().index();
             $('#tabData21 tbody tr:eq(' + _rowIndex + ')').removeClass("row__selected");
             $('#tabData22 tbody tr:eq(' + _rowIndex + ')').removeClass("row__selected");
             $(this).prop("checked", false);
             // 设置删除按钮有效
             let _event_delete_onclick = "_InstancePageLinesAssortment.DoDeleteLines($(this))";
             $row.children('td').eq(2).children('span').eq(0).attr("onclick", _event_delete_onclick);
             
             $('#tabData21 tbody tr:eq(' + _rowIndex + ')').find("td").eq(3).html("<span class='n1'>是");
             $('#tabData21 tbody tr:eq(' + _rowIndex + ')').removeClass("row__error");
             $('#tabData22 tbody tr:eq(' + _rowIndex + ')').removeClass("row__error");
             });*/
            $("#CheckAll").prop("checked", false);
            $("#lines_sort").val("0");
            $("#lines_filter").val("-1");
            ShowSuccessMessagePanel("搭配计算完成。");
        }
    }
    // 同步单耗表
    UpdateLinesForSyncBom() {
        let _params = {};
        _params['HeaderId'] = parseInt($("#HeaderId").val());
        _params['MoHeaderId'] = parseInt($.trim($("#MoHeaderId").val()));
        _params['StyleNo'] = $.trim($("#StyleNo").find("option:selected").text());
        _params['BomHeaderId'] = parseInt($.trim($("#BomHeaderId").val()));
        _params['UpdatedBy'] = parseInt($("#UserId").val());
        super.DoAjax(_params, "/tech/mrp/lines/assortment/syncbom.html", function (data, _this) {
            $("#CheckAll").prop("checked", false);
            // 刷新搭配画面数据
            _this.BuildDataTable(data.AssortmentLinesList);
            // 刷新调达表
            _InstancePageLinesMrp.BuildDataTable(data.MrpLinesList);
            ShowSuccessMessagePanel("同步完成。");
        });
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = 219;
        let _rc = Math.floor((h - _tabTop - 25) / 25);
        let _dh = _rc * 25 + 17;
        let _rowH = this.rows * 25 + 17; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD21").css({"max-height": _dh - 17, height: _dh - 17});
        $("#divD22").css({"max-height": _dh + 1, height: _dh + 1});
    }
    ScrollTo() {
        $('#divH22').scrollLeft($('#divD22').scrollLeft());
        $('#divD21').scrollTop($('#divD22').scrollTop());
    }
}

class MyPageLinesMrp extends BaseEditSlave {
    constructor() {
        super('', '', '');
    }
    BuildDataTable(result) {
        $("#tabData31 tbody").empty();
        $("#tabData32 tbody").empty();
        if (result === null) {
            return false;
        }
        let content_01 = '';
        let content_02 = '';
        this.rows = result.length;
        let _prevRowMaterialId = 0;
        let _prevRowPartOfNeed = '';
        let _prevRowSpecification = '';
        let _prevRowClass = "";
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            let _stockLevels = result[i].stockLevels === null ? 0 : result[i].stockLevels;
            let _trCss = '';
            let _editCellClass = 'class="edited-cell"';
            if (result[i].quotedFlag === true) {
                _trCss = 'class="row__quoted"';
                _editCellClass = '';
            } else {
                // 这部分内容按照材料+使用部位进行颜色区分
                if (i === 0) {
                    _prevRowMaterialId = result[i].materialId;
                    _prevRowPartOfNeed = formatNullData(result[i].partOfNeed);
                    _prevRowSpecification = formatNullData(result[i].specification);
                    _prevRowClass = 'class="row__group01"';   // #4cc368 #000
                }
                if (_prevRowMaterialId === result[i].materialId && _prevRowPartOfNeed === formatNullData(result[i].partOfNeed) && _prevRowSpecification === formatNullData(result[i].specification)) {
                    _trCss = _prevRowClass;
                } else { // #cbdcef
                    if (_prevRowClass === 'class="row__group02"')
                        _trCss = 'class="row__group01"';
                    else
                        _trCss = 'class="row__group02"';
                    _prevRowClass = _trCss;
                }
                _prevRowMaterialId = result[i].materialId;
                _prevRowPartOfNeed = formatNullData(result[i].partOfNeed);
                _prevRowSpecification = formatNullData(result[i].specification);
            }
            if (result[i].quotedFlag === true) {
                content_01 += '<tr _mash_id="' + id + '" ' + _trCss + '>';
            } else {
                if ((parseFloat(result[i].planDemandedQuantity - _stockLevels) - parseFloat(result[i].demandedQuantity === null ? 0 : result[i].demandedQuantity)) <= 1) {
                    content_01 += '<tr _mash_id="' + id + '" ' + _trCss + '>';
                } else {
                    content_01 += '<tr _mash_id="' + id + '" ' + _trCss + ' style="background-color:#FFDE00; color:#000;">';
                }
            }
            content_01 += '<td style="text-align:center;">' + result[i].orderNo + '</td>';
            content_01 += '<td _mash_materialId="' + result[i].materialId + '">' + formatNullData(result[i].materialName) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].materialCode) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].supplierName) + '</td>';
            content_01 += '<td style="text-overflow:ellipsis;" title="' + formatNullData(result[i].partOfNeed) + '">' + formatNullData(result[i].partOfNeed) + '</td>';
            content_01 += '<td style="text-overflow:ellipsis;" title="' + formatNullData(result[i].destination) + '">' + formatNullData(result[i].destination) + '</td>';            // 发货目的地
            content_01 += '</tr>';

            if ((parseFloat(result[i].planDemandedQuantity - _stockLevels) - parseFloat(result[i].demandedQuantity === null ? 0 : result[i].demandedQuantity)) <= 1) {
                content_02 += '<tr ' + _trCss + '>';
            } else {
                content_02 += '<tr ' + _trCss + ' style="background-color:#FFDE00; color:#000;">';
            }
            content_02 += '<td style="text-overflow:ellipsis;" title="' + formatNullData(result[i].productColourName) + '">' + formatNullData(result[i].productColourName) + '</td>'; // 成品色
            content_02 += '<td style="text-align:center;">' + formatNullData(result[i].productSizeName) + '</td>';   // 成品码
            content_02 += '<td ' + _editCellClass + '>' + formatNullData(result[i].materialColourName) + '</td>';    // 材料色
            content_02 += '<td>' + formatNullData(result[i].fabricWidth) + '</td>';     // 净幅
            content_02 += '<td title="' + formatNullData(result[i].specification) + '"' + _editCellClass + '>' + formatNullData(result[i].specification) + '</td>';  // 规格即毛幅
            //content_02 += '<td>' + formatNullData(result[i].customerPieceYardage === 0 ? null : result[i].customerPieceYardage) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].factoryPieceYardage === 0 ? null : result[i].factoryPieceYardage) + '</td>';     // 工厂用量
            content_02 += '<td>' + formatNullData(result[i].suitCutPieceYardage === 0 ? null : result[i].suitCutPieceYardage) + '</td>';     // 套裁量
            content_02 += '<td style="text-align:center;">' + formatNullData(result[i].uomName) + '</td>';                         // 单位
            content_02 += '<td>' + formatNullData(result[i].productQuantity) + '</td>';                                            // 成品数量
            content_02 += '<td>' + result[i].planDemandedQuantity + '</td>';                                                       // 需求量
            //content_02 += '<td>' + formatNullData(result[i].quantityOfSuitCutting) + '</td>';                                    // 套裁数
            //content_02 += '<td>' + formatNullData(result[i].quantitySuitDemand) + '</td>';                                       // 套裁需求量
            content_02 += '<td ' + _editCellClass + '>' + formatNullData(result[i].stockLevels) + '</td>';                         // 库存数
            content_02 += '<td ' + _editCellClass + '>' + result[i].demandedQuantity + '</td>';                                    // 补给数
            content_02 += '<td ' + _editCellClass + '>' + formatNullData(result[i].description) + '</td>';                         // 备注
            content_02 += '</tr>';

            $("#tabData31 tbody").append(content_01);
            $("#tabData32 tbody").append(content_02);
            content_01 = '';
            content_02 = '';
        }
        setTwoTableRowColor("tabData31", "tabData32");

        let cell_id = "_cell__field";
        let cell_name = "__cell__field";
        $('#tabData32 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), cell_id, cell_name, 0);
        });

        // 回车即保存
        $("#dataArea_04").keyup(function (e) {
            if (e.keyCode === 13) {
                $("#ButSaveLinesResult").focus();
                this.DoSave();
            }
        });

        // 自适应高度
        this.AutoAdjustTableHeightForLines();
    }
    // 取得用料需求明细（排序用）
    FetchLinesData() {
        let _params = {};
        _params["HeaderId"] = parseInt($("#HeaderId").val());
        _params["AssortmentType"] = $("#lines_filter").val();
        _params["SortType"] = $("#lines_sort").val();

        super.DoAjax(_params, "/tech/mrp/lines/result/fetchByAssortmentType.html", function (data, _this) {
            //$("#CheckAll").prop("checked", false);
            // 刷新搭配画面数据
            _this.BuildDataTable(data);
        });
    }
    // 得到物料需求数据
    GetLinesData() {
        let _result = {};
        let itemList = [];
        $('#tabData31 tbody').find("tr").each(function (index) {
            let _linesId = $(this).attr("_mash_id");
            let $tr2 = $('#tabData32 tbody').find("tr").eq(index);
            if ($(this).find("td.dirty").length > 0 || $tr2.find("td.dirty").length > 0) {
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['linesId'] = _linesId;
                // 材料颜色
                if ($tr2.find('td').eq(2).hasClass("dirty")) {
                    item['materialColourName'] = $.trim($tr2.find('td').eq(2).text());
                } else {
                    item['materialColourName'] = null;
                }
                // 规格=毛幅
                if ($tr2.find('td').eq(4).hasClass("dirty")) {
                    item['specification'] = $.trim($tr2.find('td').eq(4).text());
                } else {
                    item['specification'] = null;
                }
                // 库存数
                if ($tr2.find('td').eq(10).hasClass("dirty")) {
                    item['stockLevels'] = formatNullInputValue($.trim($tr2.find('td').eq(10).text())) === null ? 0 : formatNullInputValue($.trim($tr2.find('td').eq(10).text()));
                } else {
                    item['stockLevels'] = null;
                }
                // 实际需要量（补给数】
                if ($tr2.find('td').eq(11).hasClass("dirty")) {
                    item['demandedQuantity'] = formatNullInputValue($.trim($tr2.find('td').eq(11).text())) === null ? 0 : formatNullInputValue($.trim($tr2.find('td').eq(11).text()));
                } else {
                    item['demandedQuantity'] = null;
                }
                // 备注
                if ($tr2.find('td').eq(12).hasClass("dirty")) {
                    item['description'] = $.trim($tr2.find('td').eq(12).text());
                } else {
                    item['description'] = null;
                }
                item['updatedBy'] = $("#UserId").val();
                itemList.push(item);
            }
        });
        _result['HeaderId'] = parseInt($("#HeaderId").val());
        _result['UpdatedBy'] = parseInt($("#UserId").val());
        _result['LinesList'] = itemList;
        return JSON.stringify(_result);
    }
    SaveLines() {
        // 只有登录者=制表人 才可以操作，否则废除错误提示
        if ($("#UserId").val() !== $("#PreparedBy").val()) {
            if ($("#RoleName").val().indexOf("系统管理员") === -1) {
                ShowErrorMessagePanel('错误提示：您不是制表人，无法进行操作。');
                return false;
            }
        }
        //step 1、进行页面验证，失败则返回
        //var success_01 = CheckGridInput();
        //if (!success_01) return;

        super.SaveLines("/tech/mrp/lines/result/batch_update.html", function (data, _this) {
            // 刷新搭配画面数据
            _this.BuildDataTable(data.MrpLinesList);
            ShowSuccessMessagePanel('保存成功。');
        });
    }
    // 重新计算，主要是由于产品数以及单耗变化引起的（更新成品数量页以及物料需求明细页）
    ReCalculate() {
        // 只有登录者=制表人 才可以操作，否则废除错误提示
        if ($("#UserId").val() !== $("#PreparedBy").val()) {
            if ($("#RoleName").val().indexOf("系统管理员") === -1) {
                ShowErrorMessagePanel('错误提示：您不是制表人，无法进行操作。');
                return false;
            }
        }
        let _params = {};
        _params['HeaderId'] = parseInt($("#HeaderId").val());
        _params['BillType'] = 2;   // 辅资材
        _params['BomHeaderId'] = parseInt($.trim($("#BomHeaderId").val()));
        _params['MoHeaderId'] = parseInt($.trim($("#MoHeaderId").val()));
        _params['StyleNo'] = $.trim($("#StyleNo").find("option:selected").text());  // 取得款号
        _params['UpdatedBy'] = parseInt($("#UserId").val());
        super.DoAjax(_params, "/tech/mrp/lines/result/re_calculate.html", function (data, _this) {
            // 显示生产数量明细数据
            _InstancePageLinesMo.scheduleNode = data.ScheduleNode;
            _InstancePageLinesMo.destinationNode = data.DestinationNode;
            _InstancePageLinesMo.BuildDataTable(data.MoLinesList);
            // 显示搭配明细数据
            _InstancePageLinesAssortment.productColourNode = data.ProductColourNode;
            _InstancePageLinesAssortment.BuildDataTableHeader();
            _InstancePageLinesAssortment.BuildDataTable(data.AssortmentLinesList);
            // 显示物料需求明细
            _this.BuildDataTable(data.MrpLinesList);

            ShowSuccessMessagePanel('调达表重新计算完成。');
        });
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = 219;
        let _rc = Math.floor((h - _tabTop - 25) / 25);
        let _dh = _rc * 25 + 17;
        let _rowH = this.rows * 25 + 17; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD31").css({"max-height": _dh - 17, height: _dh - 17});
        $("#divD32").css({"max-height": _dh + 1, height: _dh + 1});
    }
    ScrollTo() {
        $('#divH32').scrollLeft($('#divD32').scrollLeft());
        $('#divD31').scrollTop($('#divD32').scrollTop());
    }
}

var _InstancePageHeader = null;
var _InstancePageLinesMo = null;
var _InstancePageLinesAssortment = null;
var _InstancePageLinesMrp = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#HeaderId").val();

    let mrp_auxiliary_list_result = $.cookie("mrp_auxiliary_list_result") === undefined ? "" : $.cookie("mrp_auxiliary_list_result");
    let _pageListData = [];
    if (mrp_auxiliary_list_result !== "") {
        _pageListData = mrp_auxiliary_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }
    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/tech/mrp/auxiliary/list.html",
            "/tech/mrp/fetchByKey.html",
            "/tech/mrp/header/save.html",
            "/tech/mrp/export.html",
            "/tech/mrp_auxiliary/print.html");

    _InstancePageLinesMo = new MyPageLinesMo();
    _InstancePageLinesAssortment = new MyPageLinesAssortment();
    _InstancePageLinesMrp = new MyPageLinesMrp();
    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelContent"});

    window.laydate.render({
        elem: '#PreparedDate',
        theme: '#393D49',
        trigger: 'click',
        done: function (value, date, endDate) {
            $("#PreparedDate").focus();
        }
    });

    // 用于导出excel文件
    $("#export_iframe").remove();
    let $iFrame = $('<iframe id="export_iframe" name="_export_iframe" style="position:absolute; top:-9999px; left:-9999px" src="javascript:false"></iframe>');
    $("body").append($iFrame);
    let $form = $('<form id="export_form" name ="_export_form" method="POST" action ="" target="_export_iframe" style="position:absolute; top:-1200px; left:-1200px"></form>');
    $('<input type="hidden" id="ExportHeaderId" name="_ExportHeaderId" value="" />').appendTo($form);
    $('<input type="hidden" id="ExportMoHeaderId" name="_ExportMoHeaderId" value="" />').appendTo($form);
    $('<input type="hidden" id="ExportBomHeaderId" name="_ExportBomHeaderId" value="" />').appendTo($form);
    $('<input type="hidden" id="ExportProductId" name="_ExportProductId" value="" />').appendTo($form);
    $('<input type="hidden" id="ExportStyleNo" name="_ExportStyleNo" value="" />').appendTo($form);
    $("body").append($form);
    // 监听iframe回调（submit()后设置iFrame加载完成事件，用于获取表单提交成功后的结果,iFrame.load(loadFunc());）
    $iFrame.on("load", function () {
        let contentWin = document.getElementById("export_iframe").contentWindow;
        let backBodyText = contentWin.document.body.innerText;
    });

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    let w = $(window).width();

    let wLeftList_1 = 530; //左边列表固定宽度
    $("#divH12").css({width: w - 16 - wLeftList_1 - 17});
    $("#divD12").css({left: -1, width: w - wLeftList_1 - 15});

    let wLeftList_2 = 908; //左边列表固定宽度
    $("#divH22").css({width: w - 16 - wLeftList_2 - 17});
    $("#divD22").css({left: -1, width: w - wLeftList_2 - 15});

    let wLeftList_3 = 670; //左边列表固定宽度
    $("#divH32").css({width: w - 16 - wLeftList_3 - 17});
    $("#divD32").css({left: -1, width: w - wLeftList_3 - 15});

    // 自适应高度
    if (_InstancePageLinesMo !== null)
        _InstancePageLinesMo.AutoAdjustTableHeightForLines();
    if (_InstancePageLinesAssortment !== null)
        _InstancePageLinesAssortment.AutoAdjustTableHeightForLines();
    if (_InstancePageLinesMrp !== null)
        _InstancePageLinesMrp.AutoAdjustTableHeightForLines();
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
    return arg !== value;
}, "Value must not equal arg.");

$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _ContractNo: "required",
            _StyleNo: {
                valueNotEquals: "-1",
                required: true
            },
            _Description: {
                valueNotEquals: "-1",
                required: true
            },
            _FinishedDate: "required"
        },
        messages: {
            _ContractNo: "请填写合同号。",
            _StyleNo: {
                valueNotEquals: "请选择款号。",
                required: "请选择款号。"
            },
            _Description: {
                valueNotEquals: "请选择单耗。",
                required: "请选择单耗。"
            },
            _FinishedDate: "请填写完成日期。"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});
// 验证输入
function CheckGridInput() {
    $('#tabData11 tbody').find("tr").each(function (index) {
        let $tr1 = $('#tabData11 tbody').find("tr").eq(index);
        let _quantity = $.trim($tr1.find('td').eq(3).text()).length > 0 ? $.trim($tr1.find('td').eq(3).text()) : 0; // 数量

        if (_quantity !== 0) {
            if (!isNumber(_quantity)) {
                GridCheckErrHandle($tr1, 3, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr1, 3);
            }
        }
    });
    $('#tabData12 tbody').find("tr").each(function (index) {
        let $tr2 = $('#tabData12 tbody').find("tr").eq(index);
        let _cmt = $.trim($tr2.find('td').eq(11).text()).length > 0 ? $.trim($tr2.find('td').eq(11).text()) : 0; //加工费

        if (_cmt !== 0) {
            if (!isNumber(_cmt)) {
                GridCheckErrHandle($tr2, 11, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr2, 11);
            }
        }
    });
    if ($('#tabData11 tbody').find('td.error').length > 0 || $('#tabData12 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}
